<?php

import('Psg.Messages');

function write_action($id) {
    if (\Psg\Auth::userExists(Psg\Core::getUserMailById($id))) {
        echo View::factory('rootTpl')
                ->set('content', 'messages_write')
                ->set('viewParams', [$id]);
    } else {
        Url::redirect();
    }
}

function delete_action($mailbox, $id) {
    if ($mailbox != ("inbox" || "outbox")) {
        Url::redirect();
    } else {
        $MsgToDel = Psg\Messages::getMessage($id, $mailbox);
        if ($mailbox == "inbox" && $MsgToDel['to'] == PSG_CURUSREUID) {
            Psg\Messages::delMessage($id, $mailbox);
        } else if ($mailbox == "outbox" && $MsgToDel['from'] == PSG_CURUSREUID) {
            Psg\Messages::delMessage($id, $mailbox);
        }
        Url::redirect('messages/' . $mailbox);
    }
}

function inbox_action() {
    echo View::factory('rootTpl')
            ->set('content', 'messages_inbox');
}

function read_action($mailbox, $id) {
    if ($mailbox != ('inbox' || 'outbox')) {
        Url::redirect();
    } else {
        $message = Psg\Messages::getMessage($id, $mailbox);
        if (!is_array($message)) {
            Url::redirect();
        } else {
            if ($message['to'] != PSG_CURUSREUID) {
                Url::redirect();
            } else {
                $message['mailbox'] = $mailbox;
                echo View::factory('rootTpl')
                        ->set('content', 'messages_read')
                        ->set('viewParams', $message);
            }
        }
    }
}